<template>
  <view class="add-goods-container">
    <view class="form-container">
      <u--form
        :model="formData"
        ref="form"
        :rules="rules"
        labelPosition="left"
        labelWidth="180"
      >
        <!-- 商品名称 -->
        <u-form-item label="商品名称" prop="prodName" required borderBottom>
          <u--input v-model="formData.prodName" placeholder="请输入商品名称" border="none" clearable></u--input>
        </u-form-item>

        <!-- 商品封面 -->
        <u-form-item label="商品封面" prop="pic" required borderBottom>
          <u-upload
            accept="image"
            :fileList="fileListPic"
            @afterRead="afterRead"
            @delete="deletePic"
            name="Pic"
            :multiple="false"
            :maxCount="1"
            width="200"
            height="200"
            imageMode="aspectFit"
          >
            <view class="uploadWp">
              <u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
              <text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
            </view>
          </u-upload>
        </u-form-item>

        <!-- 商品描述 -->
        <u-form-item label="商品描述" prop="brief" borderBottom>
          <u--textarea v-model="formData.brief" placeholder="请输入商品描述" border="none" maxlength="200" count></u--textarea>
        </u-form-item>

        <!-- 价格（两位小数） -->
        <u-form-item label="价格(元)" prop="price" required borderBottom>
          <u--input v-model="formData.price" placeholder="请输入价格，保留两位小数" border="none" type="digit" clearable></u--input>
        </u-form-item>

        <!-- 商品单位 -->
        <u-form-item label="商品单位" prop="units" required borderBottom>
          <u--input v-model="formData.units" placeholder="例如：件 / 个 / 箱" border="none" clearable></u--input>
        </u-form-item>

        <!-- 库存 -->
        <u-form-item label="库存" prop="totalStocks" required borderBottom>
          <u--input v-model="formData.totalStocks" placeholder="请输入库存数量" border="none" type="digit" clearable></u--input>
        </u-form-item>

        <!-- 排序（越大越靠前） -->
        <u-form-item label="排序" prop="weight" borderBottom>
          <u--input v-model="formData.weight" placeholder="请输入排序值，越大越靠前" border="none" type="number" clearable></u--input>
        </u-form-item>

        <!-- 销量（可选） -->
        <u-form-item label="销量" prop="soldNum" borderBottom>
          <u--input v-model="formData.soldNum" placeholder="请输入销量" border="none" type="number" clearable></u--input>
        </u-form-item>

        <!-- 校友折扣（数字） -->
        <u-form-item label="校友折扣" prop="alumniDiscount" borderBottom>
          <u--input v-model="formData.alumniDiscount" placeholder="请输入校友折扣（数字）" border="none" type="number" clearable></u--input>
        </u-form-item>

        <!-- 分销返佣（小于1，两位小数） -->
        <u-form-item label="分销返佣" prop="rebate" borderBottom>
          <u--input v-model="formData.rebate" placeholder="请输入返佣比例(0-1，两位小数)" border="none" type="number" clearable></u--input>
        </u-form-item>

        <!-- 商品状态 -->
        <u-form-item label="是否上架" prop="status" borderBottom>
          <u-switch size="45" v-model="formData.status" :activeValue="1" :inactiveValue="0"></u-switch>
        </u-form-item>

        <!-- 在线支付（固定为1，隐藏显示，仅回传） -->
<!--        <u-form-item label="在线支付" borderBottom>-->
<!--          <text class="readonly-text">开启</text>-->
<!--        </u-form-item>-->

        <!-- 商品详情图（最多3张） -->
        <u-form-item label="详情图片" prop="images" borderBottom>
          <u-upload
            accept="image"
            :fileList="fileListImages"
            @afterRead="afterRead"
            @delete="deletePic"
            name="Images"
            :multiple="true"
            :maxCount="3"
            width="200"
            height="200"
            imageMode="aspectFit"
          >
            <view class="uploadWp">
              <u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
              <text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
            </view>
          </u-upload>
        </u-form-item>
      </u--form>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-action">
      <u-button
        :loading="loading"
        :disabled="loading"
        @click="submitForm"
        type="primary"
        size="large"
        customStyle="background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%); border: none; border-radius: 44rpx;"
      >
        {{ loading ? '提交中...' : (isNew ? '新增商品' : '保存修改') }}
      </u-button>
    </view>
  </view>
</template>

<script>
import {mapGetters} from 'vuex'
import baseConfig from '@/config/baseUrl.js'

export default {
  name: 'AddMyGoods',

  computed: {
    ...mapGetters(['openId', 'userInfo'])
  },

  data() {
    return {
      isNew: true,
      loading: false,
      // 上传文件列表
      fileListPic: [],
      fileListImages: [],

      formData: {
        id: '',
        // 显示与输入
        prodName: '',
        brief: '',
        price: '',
        units: '',
        totalStocks: '',
        weight: '',
        soldNum: '',
        alumniDiscount: '',
        rebate: '', // < 1 两位小数
        status: 1,  // 1-正常 0-下架
        pic: '',    // 封面图
        images: '', // 多张详情图，逗号分隔

        // 隐藏/自动填充
        cardId: '',
        openId: '',
        shopHead: '',
        shopMobile: '',
        shopUser: '',
        onlinePay: 1
      },

      rules: {
        prodName: [{ required: true, message: '请输入商品名称', trigger: ['blur','change'] }],
        price: [
          { required: true, message: '请输入价格', trigger: ['blur','change'] },
          // { validator: (rule, value, callback) => {
          //     const s = value === 0 ? '0' : (value === null || value === undefined ? '' : String(value))
          //     if (!s) return callback(new Error('请输入价格'))
          //     if (!/^\d+(?:\.\d{1,2})?$/.test(s)) return callback(new Error('价格需为最多两位小数'))
          //     callback()
          //   }, trigger: ['blur','change'] }
        ],
        units: [{ required: true, message: '请输入商品单位', trigger: ['blur','change'] }],
        totalStocks: [
          { required: true, message: '请输入库存', trigger: ['blur','change'] },
          // { validator: (rule, value, callback) => {
          //     const s = value === 0 ? '0' : (value === null || value === undefined ? '' : String(value))
          //     if (!s && s !== '0') return callback(new Error('请输入库存'))
          //     if (!/^\d+$/.test(s)) return callback(new Error('库存需为整数'))
          //     callback()
          //   }, trigger: ['blur','change'] }
        ],
        pic: [{ required: true, message: '请上传商品封面', trigger: ['blur','change'] }],
        // rebate: [
        //   { validator: (rule, value, callback) => {
        //       if (value === '' || value === null || value === undefined) return callback()
        //       const s = String(value)
        //       if (!/^(?:0(?:\.\d{1,2})?|0?\.\d{1,2}|1(?:\.0{1,2})?)$/.test(s)) return callback(new Error('返佣需为0-1，两位小数'))
        //       callback()
        //     }, trigger: ['blur','change'] }
        // ]
      }
    }
  },

  onLoad(option) {
    this.isNew = option?.isNew == '1'
    // 绑定隐式字段
    this.formData.cardId = this.userInfo?.id || ''
    this.formData.openId = this.openId || ''
    this.formData.shopHead = this.userInfo?.head || ''
    this.formData.shopMobile = this.userInfo?.mobile || ''
    this.formData.shopUser = this.userInfo?.name || ''

    if (!this.isNew) {
      this._getGoodsDetail(option?.id)
    }
  },

  methods: {
    // 获取详情用于回显（留口）
    async _getGoodsDetail(id) {
      if (!id) return
      try {
        uni.showLoading({ title: '加载中', mask: true })
        const res = await this.$api.getProdShopDetail({ id, openId: this.openId })
        if (res && res.success && res.result) {
          const info = res.result
          // 表单回显
          this.formData = {
            id: info.id || '',
            prodName: info.prodName || '',
            brief: info.brief || '',
            // 确保为字符串，避免 number 0 被当作空
            price: (info.price === 0 || info.price) ? String(info.price) : '',
            units: info.units || '',
            totalStocks: (info.totalStocks === 0 || info.totalStocks) ? String(info.totalStocks) : '',
            weight: info.weight || '',
            soldNum: (info.soldNum === 0 || info.soldNum) ? String(info.soldNum) : '',
            alumniDiscount: (info.alumniDiscount === 0 || info.alumniDiscount) ? String(info.alumniDiscount) : '',
            rebate: (info.rebate === 0 || info.rebate) ? String(info.rebate) : '',
            status: info.status ?? 1,
            pic: info.pic || '',
            images: info.images || '',
            cardId: info.cardId || this.userInfo?.id || '',
            openId: info.openId || this.openId || '',
            shopHead: info.shopHead || this.userInfo?.head || '',
            shopMobile: info.shopMobile || this.userInfo?.mobile || '',
            shopUser: info.shopUser || this.userInfo?.name || '',
            onlinePay: info.onlinePay ?? 1
          }

          // 文件列表回显
          this.fileListPic = this.formData.pic ? [{ url: this.formData.pic, status: 'success' }] : []
          this.fileListImages = []
          if (this.formData.images) {
            const arr = this.formData.images.split(',').filter(Boolean)
            this.fileListImages = arr.map(u => ({ url: u, status: 'success' }))
          }
        } else {
          uni.showToast({ title: res?.message || '加载失败', icon: 'none' })
        }
      } catch (e) {
        uni.showToast({ title: '加载失败', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
      const fieldMap = { 'Pic': 'pic', 'Images': 'images' }
      if (fieldMap[event.name] === 'pic') {
        this.formData.pic = ''
      }
      if (fieldMap[event.name] === 'images') {
        // 重新聚合 images
        const urls = this.fileListImages.filter(i => i.url).map(i => i.url)
        this.formData.images = urls.join(',')
      }
    },

    // 新增图片
    async afterRead(event) {
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length

      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })

      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: event.name,
          url: result,
          fileName: `upload_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          filePath: result
        }))

        // 映射到表单
        if (event.name === 'Pic') {
          this.formData.pic = result
        } else if (event.name === 'Images') {
          const urls = this.fileListImages.filter(i => i.url).map(i => i.url)
          this.formData.images = urls.join(',')
        }

        fileListLen++
      }
    },

    // 上传接口
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
          filePath: url,
          name: 'file',
          success: (res) => {
            let data = JSON.parse(res.data)
            if (data.success) {
              resolve(data.message)
            } else {
              reject(new Error(data.message || '上传失败'))
            }
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    },

    // 提交
    async submitForm() {
      try {
        await this.$refs.form.validate()
      } catch (e) {
        return
      }

      // 组装并格式化数值
      const payload = {
        alumniDiscount: this.formData.alumniDiscount ? Number(this.formData.alumniDiscount) : 0,
        brief: this.formData.brief || '',
        cardId: this.formData.cardId,
        images: this.formData.images || '',
        openId: this.formData.openId,
        pic: this.formData.pic,
        price: this.formData.price ? Number(Number(this.formData.price).toFixed(2)) : 0,
        prodName: this.formData.prodName,
        status: this.formData.status,
        totalStocks: this.formData.totalStocks ? parseInt(this.formData.totalStocks) : 0,
        weight: this.formData.weight ? parseInt(this.formData.weight) : 0,
        soldNum: this.formData.soldNum ? parseInt(this.formData.soldNum) : 0,
        shopHead: this.formData.shopHead,
        shopMobile: this.formData.shopMobile,
        shopUser: this.formData.shopUser,
        rebate: this.formData.rebate ? Number(Number(this.formData.rebate).toFixed(2)) : 0,
        onlinePay: 1,
        units: this.formData.units
      }

      this.loading = true
      try {
        console.log('提交参数:', payload)
        let res = {}
        if (this.isNew){
          res = await this.$api.addMyGoods(payload)
        }else{
          let params ={
            ...payload,
             id: this.formData.id,
          }
          res = await this.$api.editMyGoods(params)
        }
        if (res.success) {
          uni.showToast({ title: this.isNew ? '新增成功' : '保存成功', icon: 'none' })
          setTimeout(() => { uni.navigateBack() }, 1200)
        } else {
          uni.showToast({ title: res.message || '提交失败', icon: 'none' })
        }
      } catch (err) {
        console.error('提交失败', err)
        uni.showToast({ title: '提交失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.add-goods-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.form-container {
  flex: 1;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.uploadWp {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #c9cdd4;
  border-radius: 12rpx;
  background-color: #fafafa;
}

.bottom-action {
  padding: 30rpx;
  background-color: #fff;
  border-top: 2rpx solid #ebeef5;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
}

// uView 表单项样式调整
::v-deep .u-form-item {
  padding: 30rpx 24rpx;
  .u-form-item__label {
    font-size: 28rpx;
    font-weight: 500;
    color: #303133;
  }
}

::v-deep .u-input {
  font-size: 28rpx;
  color: #303133;
}

::v-deep .u-textarea {
  .u-textarea__textarea {
    font-size: 28rpx;
    color: #303133;
  }
}

::v-deep .u-upload {
  .u-upload__button { margin-right: 0; }
}

.readonly-text {
  font-size: 28rpx;
  color: #606266;
}
</style>
